package org.wevil.anno;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import org.wevil.entity.sys.SysDataDict;
import org.wevil.repo.sys.SysDataDictRepo;
import org.wevil.util.BeanUtil;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 数据字典序列化
 */
public class DictSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                     BeanDescription beanDesc,
                                                     List<BeanPropertyWriter> beanProperties) {
        // 遍历所有字段
        for (Field field : beanDesc.getBeanClass().getDeclaredFields()) {
            field.setAccessible(true);
            // 检查是否有自定义注解
            if (field.isAnnotationPresent(Dict.class)) {
                Dict annotation = field.getAnnotation(Dict.class);
                // 添加新的虚拟字段
                beanProperties.add(new BeanPropertyWriter(
                        beanProperties.get(0) // 复用第一个字段的序列化配置
                ) {
                    @Override
                    public String getName() {
                        return field.getName()+"_text"; // 字段名
                    }

                    @Override
                    public void serializeAsField(Object bean, com.fasterxml.jackson.core.JsonGenerator gen,
                                                 com.fasterxml.jackson.databind.SerializerProvider prov) throws Exception {
                        SysDataDictRepo dataDictRepo = BeanUtil.getBean(SysDataDictRepo.class);
                        SysDataDict sysDataDict = dataDictRepo.findByDictCodeAndDictKey(annotation.value(), field.get(bean).toString());
                        String value = "";
                        if(sysDataDict !=null){
                            value = sysDataDict.getDictValue();
                        }
                        // 写入自定义字段值
                        gen.writeStringField(field.getName()+"_text", value);
                    }
                });
            }
        }
        return beanProperties;
    }
}
